package github.full_stack_notes;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class ReflectDemo {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 方式一
        Class<Date> dateClass = Date.class;
        Class<Integer> integerClass = int.class;

        // 方式二（常用）
        Date date = new Date();
        Class<? extends Date> aClass = date.getClass();

        // 方式三
        try {
            Class<?> bClass = Class.forName("java.util.Date");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Constructor<? extends Student> constructor = Student.class.getConstructor();
        Constructor<? extends Student> constructor1 = Student.class.getDeclaredConstructor(String.class, int.class);
        /* 等价于 Student s = Student.class.newInstance(); */
        Student student = constructor.newInstance();
        Student student1 = constructor1.newInstance("abc", 11);
        System.out.println("student = " + student);
        System.out.println("student1 = " + student1);

        Student s = new Student();
        Class<? extends Student> studentClass = Student.class;
        Method setName = studentClass.getDeclaredMethod("setName", String.class);
        setName.invoke(s, "haha");
        Method setAge = studentClass.getDeclaredMethod("setAge", int.class);
        setAge.invoke(s, 12);
        System.out.println("s = " + s);
    }

    static class Student {
        private String name;
        private int age;

        public Student() {
        }

        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
